package com.keruyun.controller;

import com.keruyun.base.lock.BootRedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by shynin on 18-4-25.
 */
@Controller
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/user/get")
    @ResponseBody
    public String getUser() {
        BootRedisLock lock = new BootRedisLock("key1", stringRedisTemplate);
        try {
            while (!lock.tryLock()) {
                Thread.sleep(200L);
            }
            System.out.println("线程: " + Thread.currentThread().toString() + " 获取了锁");
            Thread.sleep(10000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        return "user1";
    }

    @GetMapping("/user/{userid}")
    @ResponseBody
    public String getUserById(HttpServletRequest httpServletRequest) {
        NativeWebRequest webRequest = new ServletWebRequest(httpServletRequest);
        Map<String, String> uriTemplateVars = (Map<String, String>) webRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        return uriTemplateVars.get("userid");

    }

    @GetMapping("/getSession")
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getMaxInactiveInterval());

        return session.getId();

    }


}
